package file

import (
	"net"
	"sync"

	"github.com/oschwald/geoip2-golang"
)

// GeoIP  geo ip
type GeoIP struct {
	File string
	db   *geoip2.Reader
	sync.Mutex
}

// NewGeoIP 新建geo ip
func NewGeoIP(file string) *GeoIP {
	return &GeoIP{
		File: file,
		db:   nil,
	}
}

// open 打开
func (r *GeoIP) open() error {
	r.Lock()
	defer r.Unlock()
	if r.db == nil {
		db, err := geoip2.Open(r.File)
		if err != nil {
			return err
		}
		r.db = db
	}
	return nil
}

// Country 获取国家代码
func (r *GeoIP) Country(ip string) (string, error) {
	if err := r.open(); err != nil {
		return "", err
	}
	netIp := net.ParseIP(ip)
	if netIp == nil {
		return "", nil
	}
	record, err := r.db.Country(netIp)
	if err != nil {
		return "", err
	}
	return record.Country.IsoCode, nil
}
